// pages/myCenter/useRecord.js
const controller = require("../controllers/Controller").controller

Page({
  data: {
    type: 2,
    title: '使用记录',
    accountCouponBagId: null,
    list: [],
    pageNumber: 1,
    tabs: ['核销记录', '赠送记录'],
    selectIndex: 0,
  },

  onLoad: function (options) {
    this.setData({
      accountCouponBagId: options.accountCouponBagId,
      type: options.type,
    })

    if (options.type == 0) { //一卡通
      this.setData({
        title: '赠送记录',
        selectIndex:1
      })
      this.giveHistoryPage(true)
    } else {
      this.writeOffHistoryPage(true)
    }
    
  },
  //切换状态
  changeState(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectIndex: index,
    })
    if (index == 0) {
      this.writeOffHistoryPage(true)
    } else {
      this.giveHistoryPage(true)
    }
  },
  // 获取核销记录
  writeOffHistoryPage(isFirst = false) {
    if (isFirst) {
      this.setData({
        pageNumber: 1,
        list: []
      })
    }
    const value = {
      type: this.data.type,
      pageNumber: this.data.pageNumber,
      accountCouponBagId: this.data.accountCouponBagId
    }
    controller.writeOffHistoryPage(value).then(res => {
      res.data.list.forEach(item => {
        item.accountMobile = this.subphone(item.accountMobile)
      })
      const list = this.data.list.concat(res.data.list)

      this.setData({
        list,
        lastPage: res.data.lastPage,
        pageNumber: this.data.pageNumber + 1
      })
    })
  },

  // 获取赠送记录
  giveHistoryPage(isFirst = false) {
    if (isFirst) {
      this.setData({
        pageNumber: 1,
        list: []
      })
    }
    const value = {
      type: this.data.type,
      pageNumber: this.data.pageNumber,
      accountCouponBagId: this.data.accountCouponBagId
    }
    controller.giveHistoryPage(value).then(res => {
      res.data.list.forEach(item => {
        item.accountMobile = this.subphone(item.accountMobile)
      })
      const list = this.data.list.concat(res.data.list)
      this.setData({
        list,
        lastPage: res.data.lastPage,
        pageNumber: this.data.pageNumber + 1
      })
    })
  },

  subphone(value) {
    if (value == undefined || value.length == 0) {
      return "";
    }
    var length = value.length;
    if (length >= 3 + 4) {
      return value.substring(0, 3) + "****" + value.substring(length - 4, length);
    } else {
      return value;
    }
  },
  onReachBottom() {
    if (this.data.selectIndex == 0) {
      this.writeOffHistoryPage()
    } else {
      this.giveHistoryPage()
    }

  }
})